import {defineConfig, loadEnv} from 'vite'
import legacy from '@vitejs/plugin-legacy'
import {createVuePlugin} from 'vite-plugin-vue2'
import VitePluginVue2Suffix from "vite-plugin-vue2-suffix";
import viteCompression from 'vite-plugin-compression';
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons' // 支持svg
import path from 'path'
import vitePluginVueDeep from "./vite-replace-webpack-dev/vite-plugin-vue-deep"; // 支持解析 /deep/ ---> ::v-deep
import vitePluginChangeMain from "./vite-replace-webpack-dev/vite-plugin-change-main";
import changeRequireContext from "./vite-replace-webpack-dev/vite-plugin-require-change/changeRequireContext"; // 自定义去支持require
import changeRequire from "./vite-replace-webpack-dev/vite-plugin-require-change/changeRequire"; // 自定义去支持require
import vitePluginDynamicImport from "./vite-replace-webpack-dev/vite-plugin-dynamic-import";
import vitePluginChangeImportdev from "./vite-replace-webpack-dev/vite-plugin-change-importdev";
import {vitePluginNodeModules__RequireChange} from "./vite-replace-webpack-dev/vite-plugin-node_modules__require-change";
import vitePluginBabel from "./vite-replace-webpack-dev/vite-plugin-babel";
import wasm from "vite-plugin-wasm";
import topLevelAwait from "vite-plugin-top-level-await";
import BabelConfig_vite from "./babel.config_vite";

// https://vitejs.dev/config/
export default defineConfig(({command, mode}) => {
  let envPrefix = ['VUE_APP_', 'VITE_']
  const env = loadEnv(mode, process.cwd(), envPrefix)
  Object.keys(env).forEach(key => {
    process.env[key] = env[key]
  })
  const vueConfigJs = require('./vue.config')

  function getWebpackVarToClient() {
    const result = {}
    const value = process.env
    if (!value) {
      return result
    }
    Object.keys(value)
      .filter(key => key.startsWith(envPrefix[0]))
      .forEach(key => {
        result['process.env.' + key] = `"${value[key]}"`
      })
    return result
  }

  return {
    build:{
      target:'esnext'
    },
    base: './',
    optimizeDeps: {
      exclude: [
        "demo-wasm"
      ]
    },
    plugins: [
      createVuePlugin(),
      vitePluginBabel({
        babelConfig: BabelConfig_vite()
        // babelConfig: {
        //   configFile: path.join(__dirname, 'babel.config_vite.js')
        // }
      }),
      vitePluginVueDeep(),
      legacy({
        targets: ['ie >= 11'],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
      }),
      viteCompression(),
      VitePluginVue2Suffix(),
      createSvgIconsPlugin({
        iconDirs: [path.join(__dirname, 'src/icons/svg')],
        symbolId: 'icon-[name]',
        inject: 'body-first'
      }),
      vitePluginChangeImportdev(),
      vitePluginChangeMain(),
      ...((includes = []) => { // 这三个一起用
        return [
          vitePluginNodeModules__RequireChange(includes),
          changeRequireContext(includes),
          changeRequire(includes),
        ]
      })(['vue-codemirror-lite']),
      vitePluginDynamicImport(),
      wasm(),
      topLevelAwait({}),
    ],
    define: {
      'process.env.NODE_ENV': command === 'serve' ? '"development"' : '"production"',
      ...getWebpackVarToClient()
    },
    envPrefix,
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: (content, filePath) => {
            if (filePath === __dirname.replace(/\\/g, '/') + '/local_modules/ZhiXinLib/style/global.module.scss') {
              return content
            }
            return `@import "~@localModules/ZhiXinLib/style/global.module.scss";
          ${content}`
          }
        },
      }
    },
    server: {
      ...vueConfigJs.devServer
    },
    resolve: {
      // 配置路径别名
      alias: {
        ...vueConfigJs.configureWebpack.resolve.alias,
        '~@': require('path').resolve(__dirname, './src'), // 支持css中@
        '~@localModules': require('path').resolve(__dirname, './local_modules'), // 支持css中@
        '~element-ui': path.join(__dirname, 'node_modules/element-ui'), // 使用别名识别：~element-ui
        'vue': path.join(__dirname, 'node_modules/vue/dist/vue.esm.browser.js'),
        /** 解决element-ui 内部找不到 async-validator 模块的问题*/
        // 'async-validator': 'node_modules/async-validator/dist-web/index.js',
        // 'v-viewer': 'node_modules/v-viewer',
      },
      extensions: vueConfigJs.configureWebpack.resolve.extensions
    },
  }
})


// 兼容webpack环境变量可以使用 define属性 进行常量替换
